<?php 
/*************************************************************************
 * File Name:		BgQrcode.php
 * Author:			chenishr
 * Mail: 			chenishr@gmail.com 
 * Created Time:	Sun May  6 18:35:39 2018
 ************************************************************************/
namespace Chenishr\Qrcode;

use Closure;
use Endroid\QrCode\QrCode;

class BgQrcode{

    // qrcode 对象
    private $qrcode = null;

    // 图片句柄
    private $imgHandle = null;
    private $imageWidth = 0;
    private $imageHeight = 0;

    // 背景图
    private $bgImg = null;

    public function __construct($text = '',$bg = '') {
        $this->qrcode = new QrCode($text);

        $this->imgHandle = imagecreatefromstring($this->qrcode->writeString());
        $this->imageWidth = imagesx($this->imgHandle);
        $this->imageHeight= imagesy($this->imgHandle);

        $this->bgImg = imagecreatefrompng($bg);

        $this->_resize_image();
        $this->pix_loop(function ($x,$y){
            echo "$x,$y\n";
        });
    }

    public function gen_png(){
        // Call the native output image
        header('Content-Type: image/png');
        imagepng($this->imgHandle);
    }

    public function get_output()
    {
        ob_start();

        $this->gen_png();

        return ob_get_clean();
    }

    protected function _resize_image()
    {
        $tmpImg = imagecreate($this->imageWidth, $this->imageHeight);

        // 调整背景图的大小
        imagecopyresized(
            $tmpImg,
            $this->bgImg,
            0,
            0,
            0,
            0,
            $this->imageWidth,
            $this->imageHeight,
            imagesx($this->bgImg),
            imagesy($this->bgImg)
        );

        imagedestroy($this->bgImg);
        $this->bgImg = $tmpImg;
    }

    // 设置背景图
    private function pix_loop(Closure $callback){
        for($i = 0; $i < $this->imageWidth; $i ++){
            for($j = 0; $j < $this->imageHeight; $j ++){
                $index = imagecolorat($this->imgHandle,$i,$j);

                // 是黑色的点就做响应的处理
                if(0 === $index){
                    //$callback($i,$j);

                    $x = $i;
                    $y = $j;

                    $sourceIndex = imagecolorat($this->bgImg, $x, $y);

                    // 参数图的像素点颜色
                    $color = imagecolorsforindex($this->bgImg, $sourceIndex);

                    // 要分配的颜色
                    $color = imagecolorallocatealpha($this->imgHandle, $color['red'], $color['green'], $color['blue'], 1);

                    imagesetpixel($this->imgHandle, $x, $y, $color);
                }
            }
        }
    }

    /**
     * 当调用不存在的方法时，去调用
     * \Endroid\QrCode\QrCode 的方法
     *
     * @param $method
     * @param $params
     * @return mixed
     */
    public function __call($method, $params)
    {
        return $this->qrcode->$method(...$params);
    }
}